import type { FileObjType } from '../types/index'

// 计算文件大小
export function FormatFileSize(size: number) {
  if (!size) return '0B'
  switch (true) {
    case size >= 1024 * 1024 * 1024:
      return (size / 1024 / 1024 / 1024).toFixed(2) + 'GB'
    case size >= 1024 * 1024:
      return (size / 1024 / 1024).toFixed(2) + 'MB'
    case size >= 1024:
      return (size / 1024).toFixed(2) + 'KB'
    default:
      return size + 'B'
  }
}

/* 根据后缀判断文件类型 */
export function GetFileType(fileName: string) {
  let suffix = '' // 后缀获取
  let result: string | undefined = '' // 获取类型结果
  if (fileName) {
    const fileArr = fileName.split('.') // 根据.分割数组
    suffix = fileArr[fileArr.length - 1] // 取最后一个
  }
  if (!suffix) return false // fileName无后缀返回false
  suffix = suffix.toLocaleLowerCase() // 将后缀所有字母改为小写方便操作
  // 匹配图片
  const imgList = ['png', 'jpg', 'jpeg', 'bmp', 'gif'] // 图片格式
  result = imgList.find((item) => item === suffix)
  if (result) return 'image'
  // 匹配txt
  const txtList = ['txt']
  result = txtList.find((item) => item === suffix)
  if (result) return 'txt'
  // 匹配excel
  const excelList = ['xls', 'xlsx']
  result = excelList.find((item) => item === suffix)
  if (result) return 'excel'
  // 匹配word
  const wordList = ['doc', 'docx']
  result = wordList.find((item) => item === suffix)
  if (result) return 'word'
  // 匹配pdf
  const pdfList = ['pdf']
  result = pdfList.find((item) => item === suffix)
  if (result) return 'pdf'
  // 匹配ppt
  const pptList = ['ppt', 'pptx']
  result = pptList.find((item) => item === suffix)
  if (result) return 'ppt'
  // 匹配zip
  const zipList = ['rar', 'zip', '7z']
  result = zipList.find((item) => item === suffix)
  if (result) return 'zip'
  // 匹配视频
  const videoList = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v']
  result = videoList.find((item) => item === suffix)
  if (result) return 'video'
  // 匹配音频
  const radioList = ['mp3', 'wav', 'wmv']
  result = radioList.find((item) => item === suffix)
  if (result) return 'audio'
  // 匹配PSD文件
  const psdList = ['psd']
  result = psdList.find((item) => item === suffix)
  if (result) return 'psd'

  // 其他文件类型
  return 'other'
}

// 计算上传速度
export function FormatSpeed(file: FileObjType, chunkItem: any, progress: any) {
  if (file.progress === 0 || !chunkItem.startTime) return '0 KB/s'
  const chunkUploaded = progress.loaded
  const elapsedTime = (Date.now() - chunkItem.startTime) / 1000 // 秒
  const speed = chunkUploaded / elapsedTime / 2 // B/s
  return speed > 1024 * 1024
    ? (speed / (1024 * 1024)).toFixed(2) + ' MB/s'
    : (speed / 1024).toFixed(2) + ' KB/s'
}

// 计算剩余时间
export function FormatRemainingTime(file: FileObjType): string {
  if (file.progress === 0 || !file.startTime) return '计算中...'
  if (file.fileStatus === 'success') return '0秒'
  if (file.fileStatus === 'error') return '上传失败'
  // const elapsedTime = (Date.now() - file.startTime) / 1000 // 秒
  const remainingBytes = file.fileSize - file.uploadedSize
  const speedBytes =
    parseFloat(file.uploadSpeed) * (file.uploadSpeed.includes('MB') ? 1024 * 1024 : 1024)
  const remainingSeconds = Math.round(remainingBytes / speedBytes)

  if (remainingSeconds < 60) return `${remainingSeconds}秒`
  const minutes = Math.floor(remainingSeconds / 60)
  const seconds = remainingSeconds % 60
  return `${minutes}分${seconds}秒`
}

// 节流函数 - 限制函数在指定时间内只执行一次
export function Throttle(fn: Function, delay = 100) {
  let lastTime = 0;
  return function(...args:any) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      lastTime = now;
      // fn.apply(this, args);
      console.log('节流 500ms触发一次', now, lastTime, delay);
      fn.apply(null, args);
    }
  };
}

// 保存任务状态到本地存储，支持续传
/* function saveTasksToStorage() {
  try {
    localStorage.setItem('upload_tasks', JSON.stringify(file))
  } catch (e) {
    console.error('Failed to save tasks to storage', e)
  }
}
// 从本地存储加载任务状态
function loadTasksFromStorage() {
  try {
    const saved = localStorage.getItem('upload_tasks')
    if (saved) {
      this.requests = JSON.parse(saved)
      // 恢复待处理任务队列
      this.queue = this.requests
        .filter((r) => r.status === 'pending')
        .map((r) => ({ task: r.task, id: r.id, fileId: r.fileId }))
      this.total = this.requests.length
      this.completed = this.requests.filter(
        (r) => r.status === 'completed' || r.status === 'failed' || r.status === 'aborted',
      ).length
    }
  } catch (e) {
    console.error('Failed to load tasks from storage', e)
    localStorage.removeItem('upload_tasks')
  }
} */
// 清除本地存储的任务状态
/* function clearTasksStorage() {
  localStorage.removeItem('upload_tasks')
} */
